<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>类表参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- alert提示区域 -->
      <el-row>
        <el-alert
          title="注意只允许为三级分类设置相关参数!"
          type="warning"
          show-icon
        >
        </el-alert>
      </el-row>

      <!-- 分类选择区域 -->
      <el-row class="cate">
        <el-col>
          <span>选择商品分类: </span>
          <el-cascader
            clearable
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="parentCateChanged"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab切换栏区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数tab栏 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数的按钮 -->
          <el-button
            type="primary"
            size="medium"
            :disabled="isBtnDisabled"
            @click="showAddDialog"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="removeTag(scope.row, index)"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteBtn(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性teb栏 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加属性的按钮 -->
          <el-button
            type="primary"
            size="medium"
            :disabled="isBtnDisabled"
            @click="showAddDialog"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTabData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="removeTag(scope.row, index)"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteBtn(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addParamsFrom"
        :rules="addParamsFromRules"
        ref="addParamsFromRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsBtn">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editParamsFrom"
        :rules="editParamsFromRules"
        ref="editParamsFromRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 级联选择框分类的列表
      cateList: [],
      // 级联选择框双向绑定的id数组
      selectedKeys: [],
      // 指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // tab栏对象
      activeName: 'many',
      // 动态参数tab栏的 form表单对象
      dpramas: [],
      // 动态参数的数据
      manyTabData: [],
      // 静态属性的数据
      onlyTabData: [],
      addDialogVisible: false,
      // 添加参数的表单对象
      addParamsFrom: {},
      // 修改参数的表单验证规则
      addParamsFromRules: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' }]
      },
      editDialogVisible: false,
      // 修改参数的表单对象
      editParamsFrom: {},
      // 修改参数的表单验证规则
      editParamsFromRules: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' }]
      },
      // 缓存 要修改的参数id
      attrId: ''
    }
  },
  created() {
    this.getCataList()
  },
  methods: {
    // 获取商品分类列表的函数
    async getCataList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品列表分类失败!')
      }
      // 把响应数据,赋值给 parentCateList
      this.cateList = res.data
    },
    // 获取参数列表数据
    async getParams() {
      // 判断当前选中的是否是三级分类
      if (this.selectedKeys.length === 0) {
        this.selectedKeys = []
        this.manyTabData = []
        this.onlyTabData = []
        return
      }
      if (this.selectedKeys.length < 3) {
        this.selectedKeys = []
        this.manyTabData = []
        this.onlyTabData = []
        return this.$message.warning('只允许为三级分类设置相关参数!')
      }
      // 调接口
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败!')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    // 监听 级联选择框值改变事件 获取tab栏的参数
    parentCateChanged() {
      this.getParams()
    },
    // 监听 tab栏切换事件
    handleTabClick() {
      this.getParams()
    },
    // 监听 添加对话框的显示
    showAddDialog() {
      this.addDialogVisible = true
    },
    // 监听 添加对话框的关闭事件
    addDialogClosed() {
      this.$refs.addParamsFromRef.resetFields()
    },
    // 点击按钮添加参数
    addParamsBtn() {
      // 表单预验证
      this.$refs.addParamsFromRef.validate(async valid => {
        if (!valid) {
          return false
        }
        // 调用接口
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsFrom.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加参数失败!')
        }
        this.getParams()
        this.addDialogVisible = false
        this.$message.success('添加参数成功!')
      })
    },
    // 监听 编辑按钮的对话框显示事件
    async showEditDialog(id) {
      this.attrId = id
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败!')
      }
      this.editParamsFrom = res.data
      this.editDialogVisible = true
    },
    // 监听 编辑对话框的关闭事件
    editDialogClosed() {
      this.$refs.editParamsFromRef.resetFields()
    },
    // 监听 编辑对话框的确认按钮
    editParamsBtn() {
      // 预验证
      this.$refs.editParamsFromRef.validate(async valid => {
        if (!valid) {
          return false
        }
        // 调接口
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.attrId}`,
          this.editParamsFrom
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改参数失败!')
        }
        // 刷新页面
        this.getParams()
        // 关闭修改对话框
        this.editDialogVisible = false
        // 提示成功
        this.$message.success('修改参数成功!')
      })
    },
    // 监听 删除参数的事件
    async deleteBtn(id) {
      // 让用户确认是否要删除
      const isConfirm = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 用catech接收错误
      // 返回值 confirm确认 cancel取消
      if (isConfirm !== 'confirm') {
        return this.$message.info('删除操作已取消!')
      }
      // 调接口
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      // 判断响应结果
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败!')
      }
      // 刷新数据列表
      this.getParams()
      // 提示用户成功
      this.$message.success('删除参数成功!')
    },
    // 监听 标签的删除事件
    async removeTag(row, index) {
      // 删除标签
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
      this.$message.success('删除标签成功!')
    },
    // 监听 添加标签的input框显示事件
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick 方法的作用, 就是当页面上的元素被重新渲染之后, 才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加标签的input框 按下enter或者失去焦点触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return false
      }
      // 将文本框内的值添加到row.attr_vals标签数组中
      row.attr_vals.push(row.inputValue.trim())
      // 清空文本框,并且隐藏
      row.inputVisible = false
      row.inputValue = ''
      // 如果没有return则证明输入内容,需要调用接口
      this.saveAttrVals(row)
      this.$message.success('添加标签成功!')
    },
    // 将对attr_vals标签素组的操作抽离出来
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('添加标签失败!')
      }
    }
  },
  // 计算属性
  computed: {
    // 如果按钮被禁用, 则返回true, 否则返回false
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true
      }
      return false
    },
    // 如果级联选择框选中三级分类,则返回三级分类的id, 否则返回null
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  margin-top: 15px;
}
.cate {
  margin: 20px 0;
}
.el-tag {
  margin: 0 10px;
}
.input-new-tag {
  width: 90px;
}
</style>
